package com.lzyx;

import com.lzyx.nr.NrSerialChannel;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.rxtx.RxtxDeviceAddress;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class NettyRxTxApplication {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup eventLoopGroup = new OioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap
                .group(eventLoopGroup)
                .channel(NrSerialChannel.class)
                .handler(new SimpleChannelInboundHandler<ByteBuf>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                        byte[] bytes = new byte[msg.readableBytes()];
                        msg.readBytes(bytes);
                        String s = new String(bytes, StandardCharsets.UTF_8);
                        log.info("收到信息:{}", s);
                    }
                })
                .remoteAddress(new RxtxDeviceAddress("COM7"))

        ;


        ChannelFuture channelFuture = bootstrap.connect();
        String msg = "hello, usr";
        ByteBuf byteBuf = Unpooled.wrappedBuffer(msg.getBytes(StandardCharsets.UTF_8));
        channelFuture.channel().writeAndFlush(byteBuf);
        channelFuture.sync();


    }
}
